package cn.itcast.bos.web.action.take_delivey;


import cn.itcast.bos.web.utils.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class ImageAction extends BaseAction<Object> {

    private File imgFile;
    private String imgFileFileName;
    private String imgFileContentType;

    public void setImgFile(File imgFile) {
        this.imgFile = imgFile;
    }

    public void setImgFileFileName(String imgFileFileName) {
        this.imgFileFileName = imgFileFileName;
    }

    public void setImgFileContentType(String imgFileContentType) {
        this.imgFileContentType = imgFileContentType;
    }

    @Action(value = "image_upload",results = @Result(name = SUCCESS,type = "json"))
    public String upload() throws IOException {
        System.out.println(imgFile);
        System.out.println(imgFileFileName);
        System.out.println(imgFileContentType);

        String savePath = ServletActionContext.getServletContext().getRealPath("/upload/");
        String saveUrl = ServletActionContext.getRequest().getContextPath() + "/upload/";

        UUID uuid = UUID.randomUUID();
        String ext = imgFileFileName.substring(imgFileFileName.lastIndexOf("."));
        String randomFileName = uuid + ext;

        FileUtils.copyFile(imgFile,new File(savePath+"/"+randomFileName));
        HashMap<String, Object> result = new HashMap<>();
        result.put("error",0);
        result.put("url",saveUrl+randomFileName);

        ActionContext.getContext().getValueStack().push(result);
        return SUCCESS;
    }
}
